<template>
    <fieldset>
        <legend>侦听器</legend>
        <input type="text" v-model="val">
        <h1>{{ props.testVal }}</h1>
        <button>点击</button>
        <button @click="handleClick2">点击2</button>
        <!-- <button @click="handleClick">点击3</button> -->
    </fieldset>
</template>
<script setup>
import { watch, ref, defineProps, toRefs,nextTick } from "vue"
//watch

//侦听响应式变量
let val = ref("")

watch(val, (newVal, oldVal) => {
    console.log("new----", newVal)
    console.log('old-----', oldVal)
})

//侦听props
let props = defineProps(['testVal', 'testVal2'])

// console.log(props)

//1.侦听整个props
// watch(props, (newVal, oldVal) => {
//     console.log('newProp', newVal)
//     console.log('oldProp', oldVal)
// })

//2.侦听单个prop的变化
// watch(() => props.testVal, (newVal) => {
//     console.log('newVal', newVal)
// })

//3.解构的props也可以侦听

// let { testVal2 } = toRefs(props);

// watch(testVal2,(newVal)=>{
//     console.log('newTestVal2===',newVal)
// })

//侦听多个数据
// watch([()=>props.testVal,()=>props.testVal2], (newVal,oldVal) => { 
//     console.log('-----',newVal)
//     console.log('---old---',oldVal)
// })


//侦听器函数的执行优化，同时修改多个响应式，被watch同时侦听的时候，多个修改会合并成一次watch回调来优化性能
let msg1 = ref('')
let msg2 = ref('哈哈哈')

//可以通过下面这种手段来强制触发侦听器函数进行多次回调
let handleClick2 = async() => {
    msg1.value='挪威'
    await nextTick()
    msg2.value="冰岛"

}

watch([msg1,msg2],(newVal)=>{
    console.log(newVal)
})
</script>